// webcad.js 作为主显示区所有功能的入口。其余相关文件为此服务。
//同时在html中引入方式改为 <script type="module" src="js/webcad.js"></script>
// index.js为二维显示区的所有功能入口
//



import * as THREE from './three.module.js';//包装webgl
import { TrackballControls } from './TrackballControls.js';//相机控制器
import { mainAxes,smallAxes,mainAxes_Arrow } from './helpers.js';
import {DoubleSide} from "./three.module.js";
import * as EVENT3D from "./event3d.js";
import {OCCfileGeometry} from "./OCCgeometry.js";
import {translateObject} from "./event3d.js";
import {OCCmodellingGeometry} from "./OCCgeometry.js";
// 辅助三维模块




//  初始化显示区---------------------------------------------------------
//  初始化显示区---------------------------------------------------------
//  初始化显示区---------------------------------------------------------

//设置渲染器及渲染尺寸
var width = document.getElementById('w_right').clientWidth;
var height = document.getElementById('w_right').clientHeight;
var renderer = new THREE.WebGLRenderer({alpha: true, antialias: true});
renderer.setSize(width, height);
document.getElementById('w_right').appendChild(renderer.domElement);

//设置相机
var camera = new THREE.PerspectiveCamera(45, width / height, 1, 10000);
var cameraOrtho= new THREE.OrthographicCamera(-25,25,25,-25,1,100000);
camera.position.set(100, 100, 50);//相机位置
camera.up.z = Math.PI*10;// 相机旋转


//场景初始化
var scene = new THREE.Scene();
var sceneOrtho= new THREE.Scene();


// 添加灯光_(灯光请不要随意更改)

//主显示区灯光
scene.add( new THREE.AmbientLight( 0xffffff, 0.5) );
var directionLight0 = new THREE.DirectionalLight( 0xffffff );
directionLight0.position.set( 5, 5, 5 );
scene.add( directionLight0);
//视角指示器灯光
sceneOrtho.add(new THREE.AmbientLight(0x404040));//漫反射光
var directionLight = new THREE.DirectionalLight(0xffffff);
directionLight.position.x=5;
directionLight.position.y=5;
directionLight.position.z=5;
directionLight.position.normalize();
sceneOrtho.add(directionLight);
var pointLight = new THREE.PointLight(0xffffff);
sceneOrtho.add(pointLight);


//添加控制
var controls = new TrackballControls(camera, renderer.domElement);
controls.rotateSpeed = 7; //旋转速度
controls.zoomSpeed = 6;//变焦速度
controls.panSpeed = 2; //平移速度
controls.noZoom = false;    //是否不变焦
controls.noPan = false;    //是否不平移
controls.staticMoving = true;  //是否开启移动惯性
controls.dynamicDampingFactor = 0.1;    //动态阻尼系数 就是灵敏度
controls.addEventListener('change', render);


//添加视角指示器。

cameraOrtho.position.z=10;
cameraOrtho.up=camera.up;
cameraOrtho.lookAt(scene.position);
var smallaxes=smallAxes();
sceneOrtho.add(smallaxes);


// 添加主显示区坐标系
var mainaxes=mainAxes(50);
scene.add(mainaxes);
//添加主显示区坐标系中的坐标轴
var mainAxes_arrow=mainAxes_Arrow(50);
scene.add(mainAxes_arrow);

//  载入从后端加载进来的图形-----------------
//  载入从后端加载进来的图形-----------------
//  载入从后端加载进来的图形-----------------
// var occGeometry=OCCgeometry()
// scene.add(occGeometry)

var mesh,line=OCCmodellingGeometry("./jsons/./box.json",scene);
OCCfileGeometry("./jsons/./cone.json",scene);
OCCfileGeometry("./jsons/./cylinder.json",scene);
OCCfileGeometry("./jsons/./sphere.json",scene);
OCCfileGeometry("./jsons/./torus.json",scene);

// 创建轮廓线，且要创建 geometry与edge的关系。，实现图形与轮廓线的关系 ？？？ 参考 interactive 中的三角形边缘

//　todo 测试移动物体：
var geometry0 = new THREE.BoxBufferGeometry( 40, 40, 40 );
var material0 = new THREE.MeshPhongMaterial( {color:0x004088,specular:0x004080,shininess:0.8,transparent: true, premultipliedAlpha: true, opacity:1,});//注意，因为shiness的存在才有phong的感觉。
var cube = new THREE.Mesh( geometry0, material0);
cube.castShadow = true;
cube.receiveShadow = true;
cube.position.set(70,70,0);
cube.userData='GEOMETRY';
cube.name="geometry1";
scene.add(cube);
translateObject(cube,camera,renderer,render,controls,scene);




//渲染函数
function render() {
    // 添加主显示区
    renderer.autoClear=false;
    renderer.setViewport(0,0,width,height);
    renderer.render(scene,camera);


    // todo 主显示区事件监测
    // EVENT3D.clickSelection(scene,camera);
    // EVENT3D.moveHlightEdge(scene,camera);



    //左上角视角指示器
    cameraOrtho.position.copy(camera.position);
    cameraOrtho.updateProjectionMatrix();
    cameraOrtho.lookAt(scene.position);
    renderer.setViewport(0,height-200,200,200);
    renderer.render(sceneOrtho,cameraOrtho);


}

function change_camera_2D() {
    var camera_x=camera.position.x;
    var camera_y=camera.position.y;
    var camera_z=camera.position.z;
    if(selected_xoy){                        //表示选中了xoy平面
        can_selected_reference=false;       //旋转的过程中不可以选中,要不然可能发生错乱
        selected_xoy=false;                 //开始执行后，立马取消这个面被选中的状态，否则界面刷新会再次进入if语句，导致旋转错乱
        var i=1;
        var flag_1= setInterval(function () {
            camera_to_position(camera_x,camera_y,camera_z,0,0,200,i++);
            if(i===501){
                clearInterval(flag_1);
                display_box_of_draft();
                is_selected_reference=false;//旋转完毕之后，不可以选择平面了，需要重新选择草图图标
            }
        },1);
    }
    else if(selected_xoz){
        can_selected_reference=false;
        selected_xoz=false;
        var j=1;
        var flag_2= setInterval(function () {
            camera_to_position(camera_x,camera_y,camera_z,0,200,0,j++);
            if(j===501){
                clearInterval(flag_2);
                display_box_of_draft();
                is_selected_reference=false;
            }
        },1);
    }
    else if(selected_yoz){
        can_selected_reference=false;
        selected_yoz=false;
        var k=1;
        var flag_3= setInterval(function () {
            camera_to_position(camera_x,camera_y,camera_z,200,0,0,k++);
            if(k===501){
                clearInterval(flag_3);
                display_box_of_draft();
                is_selected_reference=false;
            }
        },1);
    }
}

function camera_to_position(x1,y1,z1,x2, y2, z2, i) {
    camera.position.set((x1 - (x1 - x2) / 500 * i),
        (y1 - (y1 - y2) / 500 * i),
        (z1 - (z1 - z2) / 500 * i));
}






// window.addEventListener( 'mousemove', onMouseMove, false );

//循环渲染及控制器更新
animate();
function animate() {
    requestAnimationFrame(animate);
    render();

    //仅遍历指定的object，如1.主坐标参考系，2.视角指示器，
    EVENT3D.selected_reference(mainaxes,camera);//选择作草图的平面，注意这个刷新放在前面，要不然click可能被当作mousemove
    EVENT3D.selected_axes(mainAxes_arrow,camera);//选择坐标轴，向后端发送信息
    EVENT3D.highlightMainAxes(mainaxes,camera);//高亮主坐标系,实现草图选择。
    EVENT3D.highlightMainAxes_Arrow(mainAxes_arrow,camera);//选中坐标轴
    EVENT3D.highlightSmallAxes(smallaxes,camera);//todo 待实现：高亮视角指示器，完成视角过渡。

    //以下遍历scene中未来所有添加的物体内容
    // EVENT3D.clickSelection(scene,camera); //点击高亮
    var object5= EVENT3D.clickSelection(scene,camera); //点击高亮
    // translateObject(object5,camera,renderer,render,controls,scene);
    EVENT3D.moveHlightEdge(scene,camera);//高亮物体边缘

    change_camera_2D();
    controls.handleResize();
    controls.update();
}